//
//  PPImageTransaction.m
//  pickpic
//
//  Created by Jinxiao on 9/25/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPImageTransaction.h"

#import "PPUploadPicture.h"
#import "PPCommonPicturesUploaderManager.h"

@interface PPImageTransaction ()
@property (readwrite, nonatomic, strong) NSMutableSet *pending;
@end

@implementation PPImageTransaction

+ (instancetype)sharedInstance {
    static id instance;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        instance = self.new;
    });

    return instance;
}

- (instancetype)init {
    self = [super init];

    _pending = [[NSMutableSet alloc] init];

    return self;
}

- (NSString *)cacheDirectory {
    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"ImageTransaction"];

    BOOL isDirectory = NO;

    if(![[NSFileManager defaultManager] fileExistsAtPath:directory isDirectory:&isDirectory] || !isDirectory) {
        [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
    }

    return directory;
}

- (NSString *)imagePathForKey:(NSString *)key {
    return [[self cacheDirectory] stringByAppendingPathComponent:key];
}

- (void)prepareTransactionWithArtwork:(PPAbstractArtwork *)artwork completion:(void (^)(void))completion {
    if(artwork == nil) {
        !completion ? : completion();

        return;
    }

    UIImage *image = artwork.image;
    NSString *identifier = artwork.transactionIdentifier;

    if(image != nil && identifier != nil) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [UIImagePNGRepresentation(image) writeToFile:[self imagePathForKey:identifier] atomically:YES];

            !completion ? : completion();
        });
    } else if(artwork.URLString != nil) {
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:artwork.URLString] options:kNilOptions progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {

            if(error == nil) {
                if(artwork.image == nil) {
                    artwork.image = image;
                }

                [UIImagePNGRepresentation(image) writeToFile:[self imagePathForKey:identifier] atomically:YES];
            }

            !completion ? : completion();
        }];
    }
}

- (void)beginTransactionWithAlbumID:(PPAlbumID)albumID identifier:(NSString *)identifier key:(NSString *)key token:(NSString *)token completion:(void (^)(PPAlbumImageID, NSError *))completion {
    if(identifier == nil || key == nil || token == nil) {
        !completion ?: completion(0, [NSError errorWithDomain:@"com.pickpic.error" code:0 userInfo:nil]);
        return;
    }

    if([_pending containsObject:identifier]) {
        !completion ?: completion(0, [NSError errorWithDomain:@"com.pickpic.error" code:0 userInfo:nil]);
        return;
    }

    [_pending addObject:identifier];

    @autoreleasepool {
        PPUploadPicture *picture = [[PPUploadPicture alloc] init];
        picture.image = [self imageForKey:identifier];
        picture.fileName = identifier;
        picture.key = key;
        picture.token = token;

        [[PPCommonPicturesUploaderManager sharedInstance] uploadPicture:picture completion:^(id data, NSError *error) {

            if(error == nil) {

                [PPNetworkService getAlbumDetailsByAlbumID:@(albumID) callback:^(id data, NSError *error) {
                    [_pending removeObject:identifier];
                    
                    if(error == nil) {

                        NSNumber *pictureid = nil;

                        for(NSDictionary *picture in [data validArrayForKey:@"pictures"]) {
                            if([[picture validStringForKey:@"key"] isEqualToString:key]) {
                                pictureid = [picture validNumberForKey:@"pictureid"];
                                break;
                            }
                        }

                        if(pictureid != nil) {
                            [self endTransactionWithItendifier:identifier];

                            !completion ? : completion(pictureid.integerValue, nil);
                        } else {
                            !completion ? : completion(0, error);
                        }
                    } else {
                        !completion ? : completion(0, error);
                    }
                }];

            } else {
                [_pending removeObject:identifier];

                !completion ? : completion(0, error);
            }
        }];
    }
}

- (void)beginTransactionWithIdentifier:(NSString *)identifier key:(NSString *)key token:(NSString *)token completion:(void (^)(NSError *))completion {
    if(identifier == nil || key == nil || token == nil) {
        return;
    }

    @autoreleasepool {
        PPUploadPicture *picture = [[PPUploadPicture alloc] init];
        picture.image = [self imageForKey:identifier];
        picture.fileName = identifier;
        picture.key = key;
        picture.token = token;

        [[PPCommonPicturesUploaderManager sharedInstance] uploadPicture:picture completion:^(id data, NSError *error) {

            if(error == nil) {
                [self endTransactionWithItendifier:identifier];
            } else {
                [MobClick event:@"1001" attributes:@{@"error": error}];
            }

            !completion ? : completion(error);
        }];
    }
}

- (void)endTransactionWithItendifier:(NSString *)identifier {
    if(identifier == nil) {
        return;
    }

    [[NSFileManager defaultManager] removeItemAtPath:[self imagePathForKey:identifier] error:nil];
}

- (UIImage *)imageForKey:(NSString *)key {
    if(key == nil) {
        return nil;
    }

    UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfFile:[self imagePathForKey:key]]];

    return image;
}

- (BOOL)containsIdentifier:(NSString *)identifier {
    return [_pending containsObject:identifier];
}




- (void)beginTransactionWithupImage:(UIImage *)image key:(NSString *)key token:(NSString *)token completion:(void (^)(NSError *))completion {
    if(image == nil || key == nil || token == nil) {
        return;
    }
    
    @autoreleasepool {
        PPUploadPicture *picture = [[PPUploadPicture alloc] init];
        picture.image = image;
        picture.key = key;
        picture.token = token;
        
        [[PPCommonPicturesUploaderManager sharedInstance] uploadPicture:picture completion:^(id data, NSError *error) {
            
            if(error == nil) {
//                [self endTransactionWithItendifier:identifier];
                 PPLog(@"上传👌");
            } else {
                PPLog(@"上传图片到七牛 error = %@",error);
                [MobClick event:@"1001" attributes:@{@"error": error}];
            }
            
            !completion ? : completion(error);
        }];
    }
}

@end
